package com.lenovo.newsapp.activity;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.adobe.mobile.Analytics;
import com.adobe.mobile.Config;
import com.lenovo.newsapp.R;
import com.lenovo.newsapp.fragment.GalleriesListFragment;
import com.lenovo.newsapp.fragment.HomeListFragment;
import com.lenovo.newsapp.fragment.MailListFragment;
import com.lenovo.newsapp.fragment.StockListFragment;
import com.lenovo.newsapp.util.Const;
import com.lenovo.newsapp.util.CrashHandler;
import com.lenovo.newsapp.util.FileUtil;
import com.lenovo.newsapp.util.HttpUtil;
import com.lenovo.newsapp.util.JPushUtil;
import com.lenovo.newsapp.util.PreferenceUtil;

public class MainActivity extends BaseActivity {

	private static final String TAG = "MainActivity";
	
	private RelativeLayout content;
	private long lastTime = 0;
	private ListView leftMenuList;
	private int currentSection = -1;
	private int sectionId = 0; // 默认加载首页
	private DrawerLayout mDrawerLayout;
	private SimpleAdapter adapter;
	
	public Bitmap bitmap;
	
	//for receive customer msg from jpush server
	private MessageReceiver mMessageReceiver;

	private Fragment fragment;

	protected int currentTime;
	public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";
	public static boolean isForeground = false;
	
	private String localNewsDetailId = "";

	private Context context;
	
	private static Map<String, SoftReference<Bitmap>> imageCaches = null;
	private static FileUtil fileUtil;
	
//	private ArrayList<String> imgUrlArrayList;
	
//	private IWXAPI api;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		CrashHandler crashHandler = new CrashHandler();
		
		// /*push test end*/
		setContentView(R.layout.fragment_main);
		
		context=this;
		registerMessageReceiver(); 
		init();

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

		setLeftView();

		loadFragment();
		
		Analytics.trackState("MainActivity", null);
		
	}

	// 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
	private void init() {
		JPushInterface.init(getApplicationContext());
	}

	private void setLeftView() {
		leftMenuList = (ListView) findViewById(R.id.left_drawer);
		leftMenuList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1,
					int position, long id) {
				@SuppressWarnings("unchecked")
				HashMap<String, Object> map = (HashMap<String, Object>) parent
						.getItemAtPosition(position);
				sectionId = (Integer) map.get("id");
				mDrawerLayout.closeDrawer(leftMenuList);
				Log.v(TAG, "sectionId = "+sectionId);
//				if(sectionId != 4&&sectionId !=6){
					loadFragment();
//				}else{
//					Toast.makeText(MainActivity.this, R.string.not_been_enabled, Toast.LENGTH_LONG).show();
//				}
			}
		});

		adapter = new SimpleAdapter(this, getTab(), R.layout.menulist_item,
				new String[] { "imgSourceId", "title" }, new int[] {
						R.id.imgSectionIcon, R.id.txtSectionText });
		leftMenuList.setAdapter(adapter);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Config.pauseCollectingLifecycleData();

	}

	@Override
	protected void onResume() {
		super.onResume();
		Config.collectLifecycleData();
		Log.v(Const.DEBUG, "isChangeLanguage--" + Const.isChangeLanguage);
		if (Const.isChangeLanguage) {
			setLeftView();
			HashMap<String, Object> map = getSection(currentSection);
			// int id = (Integer) map.get("id");
			// if (null != map && id != currentSection) {

			// 设置标题
			String title = map.get("title").toString();
			actionBar.setTitle(title);
			// }
			Const.isChangeLanguage = false;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.v(TAG, "onCreateOptionsMenu...");
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {

			Intent intent = new Intent(MainActivity.this, SettingActivity.class);
			startActivity(intent);
			return true;
		} else if (id == R.id.action_refresh) {
			Log.v(Const.DEBUG, "action_refresh---");
			refreshFragment();
//			try {
//				InfoJSONParser.getInfoList(1, PreferenceUtil.getString("username", ""), Const.INIT_FLAG, this);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		} else if (id == android.R.id.home) {
			Log.v(TAG, "点击左上角按钮");
			if (mDrawerLayout.isDrawerVisible(leftMenuList)) {
				mDrawerLayout.closeDrawer(leftMenuList);
			} else {
				mDrawerLayout.openDrawer(leftMenuList);
			}
			Log.v(Const.DEBUG, mDrawerLayout.findFocus().toString() + "");
			// mDrawerLayout.closeDrawer(leftMenuList);
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	private void loadFragment() {
		Log.v(TAG, "loadFragment...");
		Log.v(TAG, "loadFragment..." + fragment);
		HashMap<String, Object> map = getSection(sectionId);
		int id = (Integer) map.get("id");

		if (null != map && id != currentSection) {
			// 设置标题
			String title = map.get("title").toString();
			actionBar.setTitle(title);

			Class<?> cls = (Class<?>) map.get("view");
//			Fragment fragment = null;

			try {
				fragment = (Fragment) cls.newInstance();

				FragmentTransaction transaction = getSupportFragmentManager()
						.beginTransaction();
				transaction.replace(R.id.content, fragment);
				transaction.commit();
				currentSection = sectionId;
				Const.setCurrentSection(sectionId);
			} catch (InstantiationException e) {
			} catch (IllegalAccessException e) {
			}
		}
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					// String s = InfoJSONParser.getGalleriesNewDetail().
					currentTime = (int) (System.currentTimeMillis());
					int a = currentTime-PreferenceUtil.getInt("offLineTime", 0);
					Log.v(TAG, "离线时间 a = "+a);
					if(a > Const.ONE_DAY_MS){
						Log.v(TAG, "离线时间"+a/60/60/1000+"小时，超过一天，重新下载离线新闻");
						downloadNewsList();
						if(success){
							Log.v(TAG, "offlinetime time= " +currentTime);
							PreferenceUtil.commitInt("offLineTime", currentTime);
							String currentId = PreferenceUtil.getString("localNewsDetailId", "")+localNewsDetailId;
							PreferenceUtil.commitString("localNewsDetailId", currentId);
						}
					}else{
						Log.v(TAG, "离线时间"+a/60/60/1000+"小时，使用旧离线新闻");
					}
					success = true;
				} catch (Exception e) {
					success = false;
					e.printStackTrace();
				}

				handler.post(new Runnable() {

					@Override
					public void run() {
						Log.v(TAG, "离线下载完毕");
//						Toast.makeText(MainActivity.this, "离线下载完毕", Toast.LENGTH_LONG).show();
					}

				});
			}
		}).start();
	}
	private void refreshFragment() {
		Log.v(Const.DEBUG, "refreshFragment---");
		HashMap<String, Object> map = getSection(sectionId);
		int id = (Integer) map.get("id");
		
		if (null != map) {
			// 设置标题
			String title = map.get("title").toString();
			actionBar.setTitle(title);
			
			Class<?> cls = (Class<?>) map.get("view");
			Fragment fragment = null;
			
			try {
				fragment = (Fragment) cls.newInstance();
				
				FragmentTransaction transaction = getSupportFragmentManager()
						.beginTransaction();
				transaction.replace(R.id.content, fragment);
				transaction.commit();
				currentSection = sectionId;
				Const.setCurrentSection(sectionId);
				Const.manuallyRefresh = true;
			} catch (InstantiationException e) {
			} catch (IllegalAccessException e) {
			}
		}
	}

	static HashMap<String, Object> getSection(int sectionId) {
		List<HashMap<String, Object>> sectionList = getTab();

		for (int i = 0; i < sectionList.size(); i++) {
			HashMap<String, Object> map = sectionList.get(i);

			int id = (Integer) map.get("id");

			if (id == sectionId) {
				return map;
			}
		}

		return null;
	}

	/**
	 * 设置tab数据
	 * 
	 * @return
	 */
	private static ArrayList<HashMap<String, Object>> getTab() {
		ArrayList<HashMap<String, Object>> sections = new ArrayList<HashMap<String, Object>>();

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("id", 0);
		map.put("name", "home");
		map.put("title", setTabLanguage(0));
		map.put("imgSourceId", R.drawable.home_page);
		map.put("view", HomeListFragment.class);
		sections.add(map);

		map = new HashMap<String, Object>();
		map.put("id", 1);
		map.put("name", "banner");
		map.put("title", setTabLanguage(1));
		map.put("imgSourceId", R.drawable.banners_news);
		map.put("view", HomeListFragment.class);
		sections.add(map);

		map = new HashMap<String, Object>();
		map.put("id", 2);
		map.put("name", "recent");
		map.put("imgSourceId", R.drawable.recent_news);
		map.put("title", setTabLanguage(2));
		map.put("view", HomeListFragment.class);
		// map.put("view", RecentListFragment.class);
		sections.add(map);

		map = new HashMap<String, Object>();
		map.put("id", 3);
		map.put("name", "gallery");
		map.put("imgSourceId", R.drawable.galleries);
		map.put("title", setTabLanguage(3));
		map.put("view", GalleriesListFragment.class);
		sections.add(map);

		map = new HashMap<String, Object>();
		map.put("id", 4);
		map.put("name", "video");
		map.put("imgSourceId", R.drawable.video);
		map.put("title", setTabLanguage(4));
		map.put("view", HomeListFragment.class);
		sections.add(map);

		map = new HashMap<String, Object>();
		map.put("id", 5);
		map.put("name", "mail");
		map.put("imgSourceId", R.drawable.ww_mail);
		map.put("title", setTabLanguage(5));
		map.put("view", MailListFragment.class);
		sections.add(map);

		map = new HashMap<String, Object>();
		map.put("id", 6);
		map.put("name", "stock");
		map.put("imgSourceId", R.drawable.stock);
		map.put("title", setTabLanguage(6));
		map.put("view", StockListFragment.class);
		sections.add(map);

		map = new HashMap<String, Object>();
		map.put("id", 7);
		map.put("name", "favorites");
		map.put("imgSourceId", R.drawable.favorite);
		map.put("title", setTabLanguage(7));
		map.put("view", HomeListFragment.class);
		sections.add(map);

		return sections;
	}

	private static String setTabLanguage(int index) {
		String l = PreferenceUtil.getString("language", "");
		Log.v("ddddd", "=== "+PreferenceUtil.getString("language", ""));
		if (l.equals("en")) {
			if (index == 0) {
				return "Home Page";
			} else if (index == 1) {
				return "Banner News";
			} else if (index == 2) {
				return "Recent News";
			} else if (index == 3) {
				return "Galleries";
			} else if (index == 4) {
				return "Video";
			} else if (index == 5) {
				return "WW Mail";
			} else if (index == 6) {
				return "Stock";
			} else if (index == 7) {
				return "Favorite";
			} else {
				return "other";
			}
		} else {
			if (index == 0) {
				return "首页";
			} else if (index == 1) {
				return "标题新闻";
			} else if (index == 2) {
				return "最近新闻";
			} else if (index == 3) {
				return "图片";
			} else if (index == 4) {
				return "视频";
			} else if (index == 5) {
				return "邮件";
			} else if (index == 6) {
				return "股票";
			} else if (index == 7) {
				return "收藏";
			} else {
				return "其他";
			}
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (System.currentTimeMillis() - lastTime > 2000) {
				Toast.makeText(this, R.string.again_logout, Toast.LENGTH_SHORT).show();
				lastTime = System.currentTimeMillis();
			} else {
				finish();
				System.exit(0);
			}

			return true;
		}

		return super.onKeyDown(keyCode, event);
	}
	
	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		registerReceiver(mMessageReceiver, filter);
	}
	
	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
              String messge = intent.getStringExtra(KEY_MESSAGE);
              String extras = intent.getStringExtra(KEY_EXTRAS);
              String title = intent.getStringExtra(KEY_TITLE);
              Log.d(TAG, "mayjtitle " + title);
              StringBuilder showMsg = new StringBuilder();
              showMsg.append(KEY_MESSAGE + " : " + title+messge + "\n");
              if (!JPushUtil.isEmpty(extras)) {
            	  showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
              }
              setCostomMsg(showMsg.toString());
			}
		}
	}
	
	private void setCostomMsg(String msg){
//		 if (null != msgText) {
//			 msgText.setText(msg);
//			 msgText.setVisibility(android.view.View.VISIBLE);
//        }
	}
	
	private void downloadNewsList() {
		String url = "";
		try {
			JSONObject jsonObj = null;
			for (int i = 0; i < 8; i++) {
				Log.v(TAG, "tab i = " + i);
				if (i == 4 || i == 6)
					continue;

				if (i == 7) {
					url = Const.DOMAIN + "/Webservice/collectList?usercode="
							+ PreferenceUtil.getString("username", "")
							+ "&page=1&pageNum=" + Const.PAGE_SIZE
							+ "&category_id="
							+ PreferenceUtil.getInt("checkedRadioBtn", 0);
				} else {
					String catalog = "";
					if (i == 0) {
						catalog = "home";
					} else if (i == 1) {
						catalog = "banner";
					} else if (i == 2) {
						catalog = "recent";
					} else if (i == 3) {
						catalog = "gallery";
					} else if (i == 5) {
						catalog = "email";
					}
					url = Const.DOMAIN + "/Webservice/newsList?catalog="
							+ catalog + "&page=1&pageNum=" + Const.PAGE_SIZE
							+ "&category_id="
							+ PreferenceUtil.getInt("checkedRadioBtn", 0);
				}
				jsonObj = HttpUtil.getJSONObjFromUrlByGet(url, false);
				PreferenceUtil.commitString(Const.SAVENEWS + "" + i,
						jsonObj.toString());

				Log.v(TAG, "tab url = " + i + "=" + url);
				JSONArray resultListArray = jsonObj.getJSONArray(Const.RESULT);
				Log.v(TAG,
						"resultListArray.length = " + resultListArray.length());
				for (int j = 0; j < resultListArray.length(); j++) {
					final String imgUrl = Const.DOMAIN
							+ resultListArray.getJSONObject(j).getString(
									"title_icon_url");
					setDownImg(imgUrl); // 缓存图片
					int news_id = resultListArray.getJSONObject(j).getInt(
							"news_id");
					localNewsDetailId += news_id + ",";
					downloadNewsDetail(news_id);
				}
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public void setDownImg(String imageUrl) {

		Log.v(TAG, "imageUrl = " + imageUrl);
		
		imageCaches = new HashMap<String, SoftReference<Bitmap>>();
		fileUtil = new FileUtil(context);
		final String filename = imageUrl
				.substring(imageUrl.lastIndexOf("/") + 1);
		final String filepath = fileUtil.getAbsolutePath() + "/" + filename;
		// Log.v(TAG, "filename = " + filename);
		// Log.v(TAG, "filepath = " + filepath);
		// 先从软引用中找
		if (imageCaches.containsKey(imageUrl)) {
			// Log.v(TAG, "软引有= ");
			SoftReference<Bitmap> reference = imageCaches.get(imageUrl);
			Bitmap bitmap = reference.get();

			// 软引用中的 Bitmap 对象可能随时被回收
			// 如果软引用中的 Bitmap 已被回收，则从文件中找
			if (bitmap != null) {

				return;
			}
		}

		// 从文件中找
		if (fileUtil.isBitmapExists(filename)) {
			// Log.v(TAG, "文件有= ");
			Bitmap bitmap = BitmapFactory.decodeFile(filepath);

			// 重新加入到内存软引用中
			imageCaches.put(imageUrl, new SoftReference<Bitmap>(bitmap));

			return;
		}
		// Log.v(TAG, "下载去= ");
		// 软引用和文件中都没有再从网络下载
//		URL u = null;
//		InputStream input = null;
//		Log.v(TAG, "imageUrl = " + imageUrl);
//		try {
//			u = new URL(imageUrl);
//		} catch (MalformedURLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		try {
//			input = (InputStream) u.getContent();
//			
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		BufferedInputStream bis = new BufferedInputStream(input);
//		BitmapFactory.Options options = new BitmapFactory.Options();
//		Bitmap bitmap = BitmapFactory.decodeStream(bis, null, options);
//
//		String imageType = options.outMimeType;
//		// 图片下载成功重新缓存
//		if (bitmap != null) {
//			// 加入到软引用中
//			imageCaches.put(imageUrl, new SoftReference<Bitmap>(bitmap));
//			// 缓存到文件系统
//			fileUtil.saveBitmap(filepath, bitmap, imageType);
//
//		}
//		try {
//			bis.close();
//			input.close();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
	}
	
	public void downloadNewsDetail(int id) {
		String url = Const.DOMAIN+"/Webservice/newsDtail?id="+id+"&usercode="+PreferenceUtil.getString("username", "");
		Log.v("ddd", url+"--");
		JSONObject r;
		try {
			r = HttpUtil.getJSONObjFromUrlByGet(url, false);
			PreferenceUtil.commitString(Const.SAVE_NEWS_DETAIL + ""+ id, r.toString());
			Log.v(TAG, "detail img url = " + r);
			if(r.getInt("status_code") == 0){
				JSONObject result = r.getJSONObject("result");
				
				JSONArray newsAttachment = result.getJSONArray("news_attachment");
				for(int i=0;i<newsAttachment.length();i++){
					JSONObject n = newsAttachment.getJSONObject(i);
					setDownImg(Const.DOMAIN+n.getString("url"));
				}
			}
			
//			final String imgUrl = Const.DOMAIN+r.getJSONObject(j).getString("title_icon_url");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			success = false;
		}
	}
	
}
